package com.realgodo.site.web;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.springside.modules.orm.Page;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;

public class ControllerSupport extends ActionSupport implements Preparable {

	/***/
	private static final long serialVersionUID = 1974351088049684306L;

	private HttpServletRequest request;

	private Map<String, Object> paramMap;

	protected Page<Object> pageInfo;

	private String pageUrl;

	private HttpSession session;

	protected String nameSpace;

	@SuppressWarnings("unchecked")
	public Map<String, Object> getParamMap() {
		if (paramMap == null) {
			paramMap = new HashMap<String, Object>(getRequest()
					.getParameterMap());
		}
		return paramMap;
	}

	@Override
	public void prepare() throws Exception {
		freemarker.log.Logger.selectLoggerLibrary(0);// 降低log的输出级别
		this.getParamMap();
	}

	public HttpServletRequest getRequest() {
		request = ServletActionContext.getRequest();
		return request;
	}

	public HttpSession getSession() {
		session = getRequest().getSession();
		return session;
	}

	public Page<Object> getPageInfo() {
		if (pageInfo == null) {
			pageInfo = new Page<Object>();
		}
		return pageInfo;
	}

	@SuppressWarnings("unchecked")
	public void setPageInfo(Page resultPage) {
		if (resultPage == null) {
			return;
		}
		if (pageInfo == null) {
			pageInfo = new Page<Object>();
		}
		pageInfo.setPageNo(resultPage.getPageNo());
		pageInfo.setTotalCount(resultPage.getTotalCount());
		pageInfo.setPageSize(resultPage.getPageSize());
	}

	public String getPageUrl() {
		if (pageUrl == null) {
			pageUrl = getRequest().getRequestURI();
		}
		return pageUrl;
	}

	public String getNameSpace() {
		String uri = getPageUrl();
		if (uri != null && !"".equals(uri.trim())) {
			String[] spaces = uri.split("/");
			if (spaces[spaces.length - 1].indexOf('?') == -1) {
				nameSpace = spaces[spaces.length - 1];
			} else if (spaces.length >= 2) {
				nameSpace = spaces[spaces.length - 2];
			}
		}
		return nameSpace;
	}
}
